// AIStepGenerator.js
import React, { useState } from 'react';
import {
    Card,
    Input,
    Button,
    List,
    message,
    Typography,
    Space,
    Progress,
    Switch,
    Alert,
    Tooltip,
    Divider,
    Tag
} from 'antd';
import {
    RobotOutlined,
    SendOutlined,
    LoadingOutlined,
    BulbOutlined,
    PlusOutlined,
    SaveOutlined,
    SyncOutlined,
    EditOutlined
} from '@ant-design/icons';
import axios from 'axios';
import {aiService} from "../../services/aiService";

const { TextArea } = Input;
const { Title, Text, Paragraph } = Typography;

const AIStepGenerator = ({ taskId, taskName = '', initialRequirements = '', onStepsGenerated, standalone = false }) => {
    const [requirements, setRequirements] = useState(initialRequirements);
    const [generatedSteps, setGeneratedSteps] = useState([]);
    const [loading, setLoading] = useState(false);
    const [useAsync, setUseAsync] = useState(true);
    const [progress, setProgress] = useState(0);
    const [error, setError] = useState(null);
    const [feedback, setFeedback] = useState('');
    const [editingStep, setEditingStep] = useState(null);

    // 生成步骤
    const generateSteps = async () => {
        if (!requirements.trim()) {
            message.error('请输入任务需求描述');
            return;
        }

        setLoading(true);
        setError(null);
        setProgress(0);

        try {
            const payload = {
                taskName: taskName || '新任务',
                requirements: requirements
            };

            if (useAsync) {
                // 模拟进度更新
                const progressInterval = setInterval(() => {
                    setProgress(prev => {
                        const newProgress = prev + Math.floor(Math.random() * 10);
                        return newProgress > 90 ? 90 : newProgress;
                    });
                }, 1000);

                // 发送异步请求获取 taskUUID
                const asyncResponse = await aiService.generateStepChainAsync(
                    payload.taskName,
                    payload.requirements
                );

                const taskUUID = asyncResponse.data.data.taskUUID;

                if (!taskUUID) {
                    throw new Error('未获取到任务ID');
                }

                // 订阅 SSE 事件
                const eventSource = aiService.subscribeToStepEvents(
                    taskUUID,
                    (result) => {
                        // 收到结果时
                        clearInterval(progressInterval);
                        setProgress(100);
                        setGeneratedSteps(result);
                        message.success('步骤生成成功！');

                        // 如果有回调函数，则调用它
                        if (onStepsGenerated) {
                            onStepsGenerated(result);
                        }

                        // 关闭 SSE 连接
                        eventSource.close();
                        setLoading(false);
                    },
                    (error) => {
                        // 发生错误时
                        clearInterval(progressInterval);
                        setError('生成步骤失败，请稍后重试');
                        message.error('生成步骤失败，请稍后重试');
                        setLoading(false);
                    }
                );

                // 添加超时处理
                setTimeout(() => {
                    if (eventSource.readyState !== 2) { // 2 表示已关闭
                        eventSource.close();
                        clearInterval(progressInterval);
                        setError('生成步骤超时，请稍后重试');
                        message.error('生成步骤超时，请稍后重试');
                        setLoading(false);
                    }
                }, 120000); // 2分钟超时
            } else {
                // 同步请求处理逻辑
                // 同步请求处理逻辑
                const response = await aiService.generateStepChain(
                    payload.taskName,
                    payload.requirements
                );
                console.info(response);

// 获取步骤数据并格式化
                const stepsData = response.data || [];
                const formattedSteps = stepsData.map((step, idx) => ({
                    name: step.name || `步骤 ${idx + 1}`,
                    description: step.description || '',
                    status: step.status || 'pending'
                }));

                setGeneratedSteps(formattedSteps);
                message.success('步骤生成成功！');

// 如果有回调函数，则调用它
                if (onStepsGenerated) {
                    onStepsGenerated(formattedSteps);
                }
                setLoading(false);
            }
        } catch (err) {
            console.error('生成步骤失败:', err);
            setError('生成步骤失败，请稍后重试');
            message.error('生成步骤失败，请稍后重试');
            setLoading(false);
        }
    };

    // 优化步骤
    const optimizeSteps = async () => {
        if (!generatedSteps.length) {
            message.error('没有可优化的步骤');
            return;
        }

        if (!feedback.trim()) {
            message.error('请输入优化反馈');
            return;
        }

        setLoading(true);
        setError(null);

        try {
            const response = await axios.post('/api/ai/optimize-steps', {
                existingSteps: generatedSteps,
                feedback: feedback
            });

            setGeneratedSteps(response.data.data);
            message.success('步骤优化成功！');
            setFeedback('');

            // 如果有回调函数，则调用它
            if (onStepsGenerated) {
                onStepsGenerated(response.data.data);
            }
        } catch (err) {
            console.error('优化步骤失败:', err);
            setError('优化步骤失败，请稍后重试');
            message.error('优化步骤失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 调整步骤
    const adjustSteps = async (progressUpdate, challenges) => {
        if (!generatedSteps.length) {
            message.error('没有可调整的步骤');
            return;
        }

        setLoading(true);
        setError(null);

        try {
            const response = await axios.post('/api/ai/adjust-steps', {
                currentSteps: generatedSteps,
                progressUpdate: progressUpdate,
                challenges: challenges
            });

            setGeneratedSteps(response.data.data);
            message.success('步骤调整成功！');

            // 如果有回调函数，则调用它
            if (onStepsGenerated) {
                onStepsGenerated(response.data.data);
            }
        } catch (err) {
            console.error('调整步骤失败:', err);
            setError('调整步骤失败，请稍后重试');
            message.error('调整步骤失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 保存步骤到任务
    const saveStepsToTask = async () => {
        if (!generatedSteps.length) {
            message.error('没有可保存的步骤');
            return;
        }

        if (!taskId && !standalone) {
            message.error('缺少任务ID，无法保存步骤');
            return;
        }

        setLoading(true);

        try {
            // 这里应该调用保存步骤的API
            const response = await axios.post(`/api/tasks/${taskId}/steps/batch`, generatedSteps);
            message.success('步骤保存成功！');

            // 如果有回调函数，则调用它
            if (onStepsGenerated) {
                onStepsGenerated(response.data.data);
            }
        } catch (err) {
            console.error('保存步骤失败:', err);
            message.error('保存步骤失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 编辑步骤
    const startEditingStep = (step, index) => {
        setEditingStep({
            index,
            ...step
        });
    };

    const updateEditingStep = (field, value) => {
        setEditingStep(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const saveEditingStep = () => {
        if (!editingStep) return;

        const updatedSteps = [...generatedSteps];
        updatedSteps[editingStep.index] = {
            id: editingStep.id,
            name: editingStep.name,
            description: editingStep.description,
            status: editingStep.status || 'pending'
        };

        setGeneratedSteps(updatedSteps);
        setEditingStep(null);
        message.success('步骤已更新');
    };

    const cancelEditingStep = () => {
        setEditingStep(null);
    };

    return (
        <Card
            title={
                <Space>
                    <RobotOutlined style={{ fontSize: '20px', color: '#1890ff' }} />
                    <span>AI步骤生成器</span>
                </Space>
            }
            style={{ width: '100%' }}
        >
            <Space direction="vertical" style={{ width: '100%' }}>
                {error && (
                    <Alert
                        message="错误"
                        description={error}
                        type="error"
                        showIcon
                        closable
                    />
                )}

                <div>
                    <Text strong>任务需求描述</Text>
                    <TextArea
                        rows={4}
                        placeholder="请详细描述任务需求，AI将根据描述生成步骤..."
                        value={requirements}
                        onChange={(e) => setRequirements(e.target.value)}
                        disabled={loading}
                    />
                </div>

                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Space>
                        <Switch
                            checked={useAsync}
                            onChange={setUseAsync}
                            disabled={loading}
                        />
                        <Tooltip title="异步模式适合复杂任务，可以在后台生成步骤">
                            <Text>使用异步生成</Text>
                        </Tooltip>
                    </Space>

                    <Button
                        type="primary"
                        icon={loading ? <LoadingOutlined /> : <SendOutlined />}
                        onClick={generateSteps}
                        loading={loading}
                    >
                        生成步骤
                    </Button>
                </div>

                {loading && useAsync && (
                    <div style={{ marginTop: 16 }}>
                        <Progress percent={progress} status="active" />
                        <Text type="secondary">AI正在生成步骤，请稍候...</Text>
                    </div>
                )}

                {generatedSteps.length > 0 && (
                    <div style={{ marginTop: 16 }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                            <Title level={5}>生成的步骤</Title>
                            {taskId && (
                                <Button
                                    type="primary"
                                    icon={<SaveOutlined />}
                                    onClick={saveStepsToTask}
                                    disabled={loading}
                                >
                                    保存到任务
                                </Button>
                            )}
                        </div>

                        <List
                            bordered
                            dataSource={generatedSteps}
                            renderItem={(step, index) => (
                                <List.Item
                                    actions={[
                                        <Button
                                            icon={<EditOutlined />}
                                            size="small"
                                            onClick={() => startEditingStep(step, index)}
                                        >
                                            编辑
                                        </Button>
                                    ]}
                                >
                                    {editingStep && editingStep.index === index ? (
                                        <div style={{ width: '100%' }}>
                                            <Input
                                                value={editingStep.name}
                                                onChange={(e) => updateEditingStep('name', e.target.value)}
                                                placeholder="步骤名称"
                                                style={{ marginBottom: 8 }}
                                            />
                                            <TextArea
                                                value={editingStep.description}
                                                onChange={(e) => updateEditingStep('description', e.target.value)}
                                                placeholder="步骤描述"
                                                rows={3}
                                                style={{ marginBottom: 8 }}
                                            />
                                            <Space>
                                                <Button type="primary" size="small" onClick={saveEditingStep}>
                                                    保存
                                                </Button>
                                                <Button size="small" onClick={cancelEditingStep}>
                                                    取消
                                                </Button>
                                            </Space>
                                        </div>
                                    ) : (
                                        <List.Item.Meta
                                            title={
                                                <Space>
                                                    <span>{`步骤 ${index + 1}: ${step.name}`}</span>
                                                    {step.status && (
                                                        <Tag color={
                                                            step.status === 'completed' ? 'green' :
                                                                step.status === 'in_progress' ? 'blue' : 'orange'
                                                        }>
                                                            {
                                                                step.status === 'completed' ? '已完成' :
                                                                    step.status === 'in_progress' ? '进行中' : '待处理'
                                                            }
                                                        </Tag>
                                                    )}
                                                </Space>
                                            }
                                            description={step.description}
                                        />
                                    )}
                                </List.Item>
                            )}
                        />

                        <Divider />

                        <div style={{ marginTop: 16 }}>
                            <Text strong>优化建议</Text>
                            <TextArea
                                rows={3}
                                placeholder="输入优化建议，AI将调整生成的步骤..."
                                disabled={loading}
                                value={feedback}
                                onChange={(e) => setFeedback(e.target.value)}
                                style={{ marginBottom: 8 }}
                            />
                            <Button
                                type="default"
                                icon={<BulbOutlined />}
                                onClick={optimizeSteps}
                                disabled={loading || !feedback.trim()}
                            >
                                优化步骤
                            </Button>
                        </div>

                        <div style={{ marginTop: 16 }}>
                            <Text strong>进度更新与挑战</Text>
                            <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
                                <TextArea
                                    rows={2}
                                    placeholder="描述当前进度..."
                                    disabled={loading}
                                    id="progress-update"
                                    style={{ flex: 1 }}
                                />
                                <TextArea
                                    rows={2}
                                    placeholder="描述遇到的挑战..."
                                    disabled={loading}
                                    id="challenges"
                                    style={{ flex: 1 }}
                                />
                            </div>
                            <Button
                                type="default"
                                icon={<SyncOutlined />}
                                onClick={() => adjustSteps(
                                    document.getElementById('progress-update').value,
                                    document.getElementById('challenges').value
                                )}
                                disabled={loading}
                            >
                                调整步骤
                            </Button>
                        </div>
                    </div>
                )}
            </Space>
        </Card>
    );
};

export default AIStepGenerator;
